package cn.ncu.wechat.service.impl;

import cn.ncu.wechat.dao.CouponRecordMapper;
import cn.ncu.wechat.model.*;
import cn.ncu.wechat.model.dto.CouponRecordDTO;
import cn.ncu.wechat.util.Result;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ncu.wechat.service.CouponService;
import cn.ncu.wechat.dao.CouponMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author 
* @description 针对表【coupon(优惠券表)】的数据库操作Service实现
* @createDate 2025-01-07 16:07:41
*/
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon>
    implements CouponService{
    @Autowired
    private CouponRecordMapper couponRecordMapper;

    @Autowired
    private CouponMapper couponMapper;


    @Override
    public Result getCouponList(Integer page, Integer pageSize, Integer status) {
        try {
            if (status != 1 && status != 2 && status != 3) {
                return Result.error(400,"status只能是1或2或3");
            }
            Page<Coupon> pageParam = new Page<>(page, pageSize);
            LambdaQueryWrapper<Coupon> lambdaQuery = new LambdaQueryWrapper<>();
            lambdaQuery.select(Coupon::getId, Coupon::getName, Coupon::getType, Coupon::getValue, Coupon::getMinAmount, Coupon::getStartTime, Coupon::getEndTime, Coupon::getTotalCount, Coupon::getUsedCount, Coupon::getStatus);
            lambdaQuery.eq(Coupon::getStatus, status);
            Page<Coupon> pageResult = page(pageParam, lambdaQuery);
            return Result.success(pageResult);
        } catch (Exception e) {
            return Result.error(500,"获取失败");
        }
    }

    @Override
    public Result addOrUpdateCoupon(Map<String, Object> request) {
        try {
            Long id = null;

            // 参数提取
            String name = (String) request.get("name");
            String startTime = (String) request.get("startTime");
            String endTime = (String) request.get("endTime");
            Integer type = (Integer) request.get("type");
            BigDecimal value = request.get("value") != null ?
                    new BigDecimal(String.valueOf(request.get("value"))) : null;
            BigDecimal min_amount = request.get("minAmount") != null ?
                    new BigDecimal(String.valueOf(request.get("minAmount"))) : null;
            Integer totalCount = (Integer) request.get("totalCount");
            Integer status = (Integer) request.get("status");

            // 参数校验
            if (StringUtils.isBlank(name)) {
                return Result.error(400, "参数 'name' 不能为空");
            }
            if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)) {
                return Result.error(400, "参数 'startTime' 和 'endTime' 不能为空");
            }
            if (type == null || (type != 1 && type != 2)) {
                return Result.error(400, "参数 'type' 必须是 1 或 2");
            }
            if (value == null || value.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error(400, "参数 'value' 必须大于 0");
            }
            if (min_amount == null || min_amount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error(400, "参数 'minAmount' 不能小于 0");
            }
            if (totalCount == null || totalCount <= 0) {
                return Result.error(400, "参数 'totalCount' 必须大于 0");
            }
            if (status == null || (status != 1 && status != 2 && status != 3)) {
                return Result.error(400, "参数 'status' 必须是 1 或 2 或 3");
            }

            // 如果包含 id 参数，进行类型转换
            if (request.containsKey("id")) {
                Object idObj = request.get("id");
                if (idObj instanceof Number) {
                    id = ((Number) idObj).longValue();
                } else {
                    return Result.error(400, "参数 'id' 类型错误");
                }
            }

            // 日期格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 根据实际日期格式修改
            Date startDate = null;
            Date endDate = null;

            try {
                // 将 startTime 和 endTime 转换为 Date 类型
                startDate = sdf.parse(startTime);
                endDate = sdf.parse(endTime);
            } catch (Exception e) {
                return Result.error(400, "日期格式错误，请使用 'yyyy-MM-dd HH:mm:ss' 格式");
            }

            Coupon coupon = new Coupon();
            coupon.setName(name);
            coupon.setType(type);
            coupon.setValue(value);
            coupon.setMinAmount(min_amount);
            coupon.setStartTime(startDate);
            coupon.setEndTime(endDate);
            coupon.setTotalCount(totalCount);
            coupon.setStatus(status);

            if (id == null) { // 新增逻辑
                boolean success = save(coupon);
                if (success) {
                    return Result.success();
                } else {
                    return Result.error(500, "添加失败");
                }
            } else { // 更新逻辑
                Coupon exist_coupon = getById(id);
                if (exist_coupon == null) {
                    return Result.error(400, "该id不存在");
                }
                coupon.setId(id);
                boolean updated = updateById(coupon);
                if (updated) {
                    return Result.success();
                } else {
                    return Result.error(500, "编辑失败");
                }
            }
        } catch (Exception e) {
            return Result.error(500, "新增或编辑失败：" + e.getMessage());
        }
    }

    @Override
    public Result voidCoupon(Long id, Map<String, String> request) {
        try {
            if (id == null) {
                return Result.error(400, "id不能为空");
            }
            Coupon exist_coupon = getById(id);
            if (exist_coupon == null) {
                return Result.error(400,"查询不到对应优惠券");
            }
            if (request.containsKey("reason") && !StringUtils.isBlank(request.get("reason"))) {
                exist_coupon.setStatus(3);
                boolean void_success = updateById(exist_coupon);
                if (void_success) {
                    return Result.success();
                } else {
                    return Result.error(500,"作废失败");
                }
            } else {
                return Result.error(400, "作废理由不能为空");
            }
        } catch (Exception e) {
            return Result.error(500,"作废失败" + e.getMessage());
        }
    }

    public Result<?> getUsageRecordsByOpenId(Integer id,Integer page,Integer pageSize,Integer status){
        if (page<=0||page==null||pageSize<=0||pageSize==null){
            return Result.error(400,"参数错误");
        }
        Page<CouponRecordDTO> pageInfo = new Page<>(page,pageSize);
        Page<CouponRecordDTO> couponRecordDTOIPage = couponRecordMapper.selectCouponRecordPageByOpenId(pageInfo,id,status);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",couponRecordDTOIPage.getRecords());
        jsonObject.put("total",couponRecordDTOIPage.getTotal());
        return Result.success(jsonObject);
    }

//    @Override
//    public Result<?> couponStatistics() {
//        List<Coupon> coupons = baseMapper.selectList(new QueryWrapper<>());
//
//        // 2. 统计总发放数量、总使用数量、过期数量
//        int totalIssued = 0;
//        int totalUsed = 0;
//        int totalExpired = 0;
//
//        for (Coupon coupon : coupons) {
//            totalIssued += coupon.getTotalCount();
//            totalUsed += coupon.getUsedCount();
//            if (coupon.getStatus() == 3) { // 假设状态3表示过期
//                totalExpired++;
//            }
//        }
//
//        // 3. 计算使用率
//        double useRate = totalIssued == 0 ? 0 : (double) totalUsed / totalIssued;
//        useRate = Double.parseDouble(String.format("%.2f", useRate));
//        // 4. 按类型统计
//        Map<Integer, Integer> typeIssuedMap = new HashMap<>();
//        Map<Integer, Integer> typeUsedMap = new HashMap<>();
//
//        for (Coupon coupon : coupons) {
//            int type = coupon.getType();
//            typeIssuedMap.put(type, typeIssuedMap.getOrDefault(type, 0) + coupon.getTotalCount());
//            typeUsedMap.put(type, typeUsedMap.getOrDefault(type, 0) + coupon.getUsedCount());
//        }
//
//        // 5. 构建类型统计列表
//        List<Map<String, Object>> typeStats = new ArrayList<>();
//        for (Map.Entry<Integer, Integer> entry : typeIssuedMap.entrySet()) {
//            int type = entry.getKey();
//            int issuedCount = entry.getValue();
//            int usedCount = typeUsedMap.getOrDefault(type, 0);
//            double typeUseRate = issuedCount == 0 ? 0 : (double) usedCount / issuedCount;
//            typeUseRate = Double.parseDouble(String.format("%.2f", typeUseRate));
//            Map<String, Object> typeStat = new HashMap<>();
//            typeStat.put("type", type);
//            typeStat.put("typeName", type == 1 ? "折扣券" : "满减券");
//            typeStat.put("issuedCount", issuedCount);
//            typeStat.put("usedCount", usedCount);
//            typeStat.put("useRate", typeUseRate);
//            typeStats.add(typeStat);
//        }
//
//
//
//        // 6. 构建响应数据
//        Map<String, Object> response = new HashMap<>();
//        Map<String, Object> overview = new HashMap<>();
//        overview.put("totalIssued", totalIssued);
//        overview.put("totalUsed", totalUsed);
//        overview.put("totalExpired", totalExpired);
//        overview.put("useRate", useRate);
//
//        response.put("overview", overview);
//        response.put("typeStats", typeStats);
//
//        return Result.success(response);
//    }


    @Override
    public Result<?> couponStatistics(String startDate, String endDate) {
        try {
            CouponStatistics couponStatistics = new CouponStatistics();
            ArrayList<CouponDailyStats> dailyStat = couponMapper.getDailyStat(startDate,endDate);
            CouponOverview overview = couponMapper.getCouponOverView(startDate,endDate);
            ArrayList<CouponTypeStats> typeStats = couponMapper.getTypeStats(startDate,endDate);
            couponStatistics.setOverview(overview);
            couponStatistics.setTypeStats(typeStats);
            couponStatistics.setDailyStats(dailyStat);
            return Result.success(couponStatistics);
        } catch (Exception e){
            return Result.error(500,"服务器错误"+e);
        }
    }
}




